<?php
/**
 * Created by PhpStorm.
 * User: HHZ
 * Date: 2018/12/21
 * Time: 14:33
 */

namespace Biz\service\activity;

use Biz\cache\activity\WeekPurchase as cWeekPurchase;
use Biz\model\SelectGoodsLog as mSelectGoodsLog;
use Biz\model\ShopFavorite as mShopFavorite;
use Biz\model\ShopSpecial as mShopSpecial;
use Biz\model\ShopSpecialGoods as mShopSpecialGoods;
use Biz\model\trade\Cart as mCart;
use Biz\model\trade\CartV as mCartV;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\service\Goods as sGoods;
use Biz\service\ShopInfo as sShopInfo;
use Biz\service\Sku as sSku;
use Biz\tools\BizUrl as tBizUrl;
use Doraemon\model\Category as mCategory;
use Medoo\Medoo;

/**
 * @deprecated
 */
class WeekPurchase
{
    /**
     * 商家直降活动列表页面
     * @param $params
     * @return array
     */
    public static function admGetWeekPurchaseList($params)
    {
        $weekPurchaseList   = mShopSpecial::getWeekPurchaseList($params);
        $weekPurchaseIdList = array_column($weekPurchaseList['list'], 'id');
        $weekPurchaseList['list'] = array_column($weekPurchaseList['list'], null,'id');

        $goodsCount = mShopSpecialGoods::select(['special_id', 'count' => Medoo::raw("count('id')")], [
            'AND' => [
                'special_id' => $weekPurchaseIdList,
                'status' => mShopSpecialGoods::STATUS_PASSED,
            ],
            'GROUP' => ['special_id']
        ]);

        $goodsCount = array_column($goodsCount, null, 'special_id');
        foreach ($goodsCount as $specialId => $info) {
            $weekPurchaseList['list'][$specialId]['goods_count'] = $info['count'];
        }

        return ['list' => $weekPurchaseList['list'], 'total' => $weekPurchaseList['total']];
    }

    /**
     * 获取活动基础信息
     * @param $specialId
     * @return mixed
     */
    public static function admGetWeekPurchase($specialId)
    {
        return mShopSpecial::getInfoById($specialId);
    }

    /**
     * 删除一场活动
     * @param $specialId
     * @param $adminId
     * @return bool
     */
    public static function admDelWeekPurchase($specialId, $adminId)
    {
        $count = mShopSpecialGoods::count('*', ['special_id' => $specialId, 'status' => mShopSpecialGoods::STATUS_PASSED]);
        if($count > 0) {
            return false;
        }

        $result = mShopSpecial::updateSpecialInfoById($specialId, ['status' => mShopSpecial::STATUS_DELETE, 'admin_id' => $adminId]);
        if($result) {
            return true;
        }
        return false;
    }

    /**
     * 新增或者编辑操作
     * @param $specialId
     * @param $params
     * @param $adminId
     * @return bool
     */
    public static function admSaveWeekPurchase($specialId, $params, $adminId)
    {
        $list = [
            'special_title' => $params['special_title'],
            'special_type' => mShopSpecial::TYPE_SPECIAL_REGISTER,
            'start_time' => $params['start_time'],
            'end_time' => $params['end_time'],
            'special_icon' => $params['special_icon_id'],
            'special_banner' => $params['special_banner_id'],
            'link_id' => $params['link_type'],
            'link_url' => $params['link'],
            'admin_id' => $adminId
        ];

        if(!$specialId) {
            $specialId = mShopSpecial::addSpecial($list);
        } else {
            $specialId = mShopSpecial::updateSpecialInfoById($specialId, $list);
        }

        if($specialId) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 商家直降商品列表
     * @param $params
     * @return array
     */
    public static function admGoodsList($params)
    {
        $where = array_merge($params['AND'], ['type' => ActivityInfo::ACTIVITY_TYPE_WEEK_PURCHASE,
            'status' => mSelectGoodsLog::STATUS_NORMAL,]);
        $selectGoodsLog = mSelectGoodsLog::select('*', $where);

        $goodsIds = array_unique(array_column($selectGoodsLog, 'goods_id'));
        $total = count($goodsIds);

        // 查询符合条件的数据
        $list = mShopSpecialGoods::getList(array_merge(['goods_id' => $goodsIds],
            ['status' => mShopSpecialGoods::STATUS_PASSED, 'special_id' => $params['AND']['activity_id']]),
            '*', $params['LIMIT'], $params['ORDER']);

        $goodsIds = array_column($list, 'goods_id');
        $goodsInfo = sGoods::goods($goodsIds, sGoods::FIELDS_GROUP_ADMIN); // 商品的基础信息
        $goodsInfo = self::getShopInfoByGoodsInfo($goodsInfo); // 获取商家信息
        $goodsInfo = self::getCateGoryName($goodsInfo); // 获取类目信息
        $goodsInfo = self::formatPrice($goodsIds, $selectGoodsLog, $goodsInfo); // 计算折扣
        $goodsInfo = self::getCartTotalByGoodsIds($goodsIds, $goodsInfo); // 商品的加购信息
        $goodsInfo = self::getFavTotalByGoodIds($goodsIds, $goodsInfo); // 商品的收藏信息
        $goodsInfo = self::getRegisterAndActivityId($selectGoodsLog, $goodsInfo, $list);
        $goodsInfo = self::getPreviewUrl($goodsInfo); // 获取预览链接

        return ['list' => $goodsInfo, 'total' => $total];
    }

    /**
     * 删除一个商品
     * @param $activityId
     * @param $specialGoodsId
     * @param $adminId
     * @return bool
     */
    public static function admDelGoods($activityId, $specialGoodsId, $adminId)
    {
        $goodsId = mShopSpecialGoods::get('goods_id', ['id' => $specialGoodsId, 'status' => mShopSpecialGoods::STATUS_PASSED]);

        $result = AllActivityInfo::admDelActivityByGoodsId($activityId, AllActivityInfo::ACTIVITY_TYPE_WEEK_PURCHASE, $goodsId, AllActivityInfo::ALL_ACTIVITY_TYPE_WEEK_PURCHASE);
        if(!$result) {
            return false;
        }

        $result = mSelectGoodsLog::action(function () use ($activityId, $specialGoodsId, $adminId, $goodsId) {
            $result = mShopSpecialGoods::updateSpecialGoods(['id' => $specialGoodsId], ['status' => mShopSpecialGoods::STATUS_DELECT]);
            if(!$result) {
                return false;
            }

            $result = mSelectGoodsLog::update([
                'status' => mSelectGoodsLog::STATUS_DELETE,
                'admin_id' => $adminId], [
                'activity_id' => $activityId,
                'type' => AllActivityInfo::ACTIVITY_TYPE_WEEK_PURCHASE,
                'goods_id' => $goodsId
            ])->rowCount();
            if(!$result) {
                return false;
            }
            return true;
        });

        // 删除成功后需要重置缓存的信息
        if($result) {
            self::setRecentActivity($activityId, $goodsId);
        }

        return $result;
    }

    /**
     * 存储最近参加的一场活动的信息
     * @param $activityId
     * @param $goodsId
     * @return bool
     */
    private static function setRecentActivity($activityId, $goodsId)
    {
        // 删除一个商品的时候，根据商品id查出来缓存，判断缓存的活动id是否与$activityId相等，相等的话，就删掉缓存， 查询日志表找出合适的一条数据
        $result = cWeekPurchase::getWeekPurchase($goodsId);
        if($result) {
            if($result[$goodsId]['activity_id'] == $activityId) {
                $activityId = mSelectGoodsLog::get('activity_id', [
                    'AND' => [
                        'goods_id' => $goodsId,
                        'status' => mSelectGoodsLog::STATUS_NORMAL
                    ],
                    'ORDER' => ['start_time' => 'DESC']
                ]);

                // 如果存在的话拼装数据存储缓存，否则的话，删除缓存
                if($activityId) {
                    $specialInfo = mShopSpecial::getSpecialInfoById($activityId, mShopSpecial::TYPE_SPECIAL_REGISTER, ['id', 'start_time', 'end_time', 'special_title']);
                    $items[$goodsId] =  [
                        'goods_id' => $goodsId,
                        'activity_id' => $specialInfo['id'],
                        'title' => $specialInfo['special_title'],
                        'start_time' => $specialInfo['start_time'],
                        'end_time' => $specialInfo['end_time'],
                    ];
                    cWeekPurchase::setWeekPurchase($items);
                } else {
                    cWeekPurchase::delWeekPurchase($goodsId);
                }
            }
        }


        return true;
    }

    /**
     * 获取预览链接
     * @param $goodsInfo
     * @return mixed
     */
    private static function getPreviewUrl($goodsInfo)
    {
        foreach ($goodsInfo as $info) {
            $goodsInfo[$info['goods_id']]['goods_h5_url'] = tBizUrl::h5GoodsInfo($info['goods_id']);
        }

        return $goodsInfo;
    }

    /**
     * 获取商品的报名id
     * @param $selectGoodsLog
     * @param $goodsInfo
     * @return mixed
     */
    private static function getRegisterAndActivityId($selectGoodsLog, $goodsInfo, $list)
    {
        $selectGoodsLog = array_column($selectGoodsLog, null,'goods_id');
        foreach ($selectGoodsLog as $goodsId => $goods){
            foreach ($goodsInfo as $info) {
                if($goods['goods_id'] == $info['goods_id']) {
                    $goodsInfo[$goodsId]['register_id'] = $goods['register_id'];
                }
            }

            foreach ($list as $item) {
                if($goods['goods_id'] == $item['goods_id']) {
                    $goodsInfo[$goodsId]['id'] = $item['id'];
                }
            }
        }
        return $goodsInfo;
    }

    /**
     * 获取加购总数
     * @param $goodsIds
     * @param $goodsInfo
     * @return mixed
     */
    private static function getCartTotalByGoodsIds($goodsIds, $goodsInfo)
    {
        $cartNum = mCart::admGetCartNumByGoodsIds($goodsIds);
        $cartVNum = mCartv::admGetCartNumByGoodsIds($goodsIds);
        $cartNumSum = array_merge($cartNum, $cartVNum);

        foreach ($goodsInfo as $goods) {
            $num = 0;
            foreach ($cartNumSum as $info) {
                if($goods['goods_id'] == $info['goods_id']) {
                    $num += $info['count'];
                }
            }
            $goodsInfo[$goods['goods_id']]['cart_count'] = $num;
        }

        return $goodsInfo;
    }

    /**
     * 获取收藏的总数
     * @param $goodsIds
     * @param $goodsInfo
     * @return mixed
     */
    private static function getFavTotalByGoodIds($goodsIds, $goodsInfo)
    {
        $total = mShopFavorite::getFavCountByGoodIds($goodsIds, 'obj_id');
        foreach ($goodsInfo as $goods) {
            foreach ($total as $goodsId => $goodsCount) {
                if ($goods['goods_id'] == $goodsId) {
                    $goodsInfo[$goodsId]['fav_count'] = count($total[$goodsId]) ?: 0;
                }
            }
        }

        return $goodsInfo;
    }

    /**
     * 处理折扣 活动价 原价
     * @param $goodsIds
     * @param $goodsList
     * @param $goodsInfo
     * @return mixed
     */
    public static function formatPrice($goodsIds, $goodsList, $goodsInfo)
    {
        $actualPrice = $disCount = [];
        $skuInfo = sSku::Sku($goodsIds, sSku::FIELDS_GROUP_SKU_INFO);

        foreach ($goodsList as $info) {
            if(isset($skuInfo[$info['goods_id']])) {
                foreach ($skuInfo[$info['goods_id']] as $item) {
                    if ($info['sku_id'] == $item['sku_id']) {
                        $disCount[$info['goods_id']][] = round($info['actual_price'] / $item['ori_price'], 2) * 10;
                        $actualPrice[$info['goods_id']][] = $info['actual_price'];
                    }
                }
            }
        }

        foreach ($goodsInfo as $goodsId => $value) {
            $minDisCount = isset($disCount[$goodsId]) ? min($disCount[$goodsId]) : 0;
            $maxDisCount = isset($disCount[$goodsId]) ? max($disCount[$goodsId]) : 0;
            $minActualPrice = isset($actualPrice[$goodsId]) ? min($actualPrice[$goodsId]) : 0;
            $maxActualPrice = isset($actualPrice[$goodsId]) ? max($actualPrice[$goodsId]) : 0;
            $goodsInfo[$goodsId]['activity_discount'] = $minDisCount != $maxDisCount ? $minDisCount . ' ~ ' . $maxDisCount : $minDisCount;
            $goodsInfo[$goodsId]['activity_price'] = $minActualPrice != $maxActualPrice ? $minActualPrice . ' ~ ' . $maxActualPrice : $minActualPrice;
        }

        return $goodsInfo;
    }

    /**
     * 获取商家信息
     * @param $goodsInfo
     * @return mixed
     */
    private static function getShopInfoByGoodsInfo($goodsInfo)
    {
        $shopIds = array_column($goodsInfo, 'uid');
        $shopInfo = sShopInfo::getShopInfoList($shopIds);
        foreach ($goodsInfo as $info) {
            if (isset($shopInfo[$info['uid']])) {
                $goodsInfo[$info['goods_id']]['shop_name'] = $shopInfo[$info['uid']]['name'];
            }
        }
        return $goodsInfo;
    }

    /**
     * 获取类目名称
     * @param $goodsInfo
     * @return mixed
     */
    private static function getCateGoryName($goodsInfo)
    {
        $categoryIds  = array_merge(array_column($goodsInfo, 'category_id'), array_column($goodsInfo, 'second_category_id'));
        $categoryInfo = array_column(mCategory::getCategoryList($categoryIds, null), null, 'id');

        foreach ($goodsInfo as $info) {
            $goodsInfo[$info['goods_id']]['category_name'] = $categoryInfo[$info['category_id']]['cate_name'];
            $goodsInfo[$info['goods_id']]['second_category_name'] = $categoryInfo[$info['second_category_id']]['cate_name'];
        }

        return $goodsInfo;
    }
}